package com.zjk.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjk.pojo.dto.UserDTO;
import com.zjk.pojo.user.TbUser;
import com.zjk.result.ResultResponse;
import com.zjk.user.mapper.UserMapper;
import com.zjk.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: gfk
 * @create: 2022/10/31
 * @Description:
 * @FileName: UserService
 * @History:
 * @自定义内容：
 */
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 登录  获取token  传入redis保存五分钟
     * @param userDTO
     * @return
     */
    public ResultResponse login(UserDTO userDTO) {
        //获取输入的用户名 密码
        String loginName = userDTO.getLoginName();
        String password = userDTO.getPassword();
        //将输入的数据存入queryWrapper中
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbUser::getLoginName,loginName)
                .or().eq(TbUser::getMobile,loginName);
        //查询数据
        List<TbUser> tbUsers = userMapper.selectList(queryWrapper);
        //判断输入的信息是否能查出数据
        if (tbUsers.size()==0){
            //如果数据为空 则返回失败信息
            return new ResultResponse(false,"用户名输入有误");
        }
        //判断输入的密码和数据库密码是否一致
        TbUser tbUser = tbUsers.get(0);
        if (!tbUser.getPassword().equals(password)){
            return new ResultResponse(false,"用户名输入有误");
        }
        Map map = new HashMap();
        map.put("userid",tbUser.getId());
        map.put("username",tbUser.getLoginName());
        map.put("type",tbUser.getType());
        String token = JwtUtils.createToken(tbUser.getId().toString(), tbUser.getLoginName(), map);
        map.put("token",token);
        redisTemplate.opsForValue().set("token"+tbUser.getId(),token,5, TimeUnit.MINUTES);
        return new ResultResponse(true,"登录成功",map);
    }
}
